import sys
from PyQt5 import QtWidgets as QtGui
import pyautogui
import cv2
import numpy as np
import mouser_opt
import img_detect
import img_ocr

g_mainwin = None

def cv2_on_mouse(event,x,y,flags,param):
    param.on_mouse(event,x,y,flags)

class mainwindow(QtGui.QWidget):
    m_deskimg=None
    m_ltpoint =()
    m_rbpoint=()
    m_min_x=m_min_y=m_width=m_height = 0
    def __init__(self):
         super().__init__()
         self.initUI()
    
    def initUI(self):
        self.setGeometry(100,100,200,100)
        self.setWindowTitle('PyQt')

        b = QtGui.QLabel(self)
        b.setText("设置图片，开始执行。ctrl+alt+x 停止")

        btn_succ = QtGui.QPushButton("设置'正确'")
        btn_succ.clicked.connect(lambda:self.btns_click(0))
        btn_cmit = QtGui.QPushButton("设置'提交'")
        btn_cmit.clicked.connect(lambda:self.btns_click(1))
        btn_next = QtGui.QPushButton("设置'下一题'")
        btn_next.clicked.connect(lambda:self.btns_click(2))
        btn_run = QtGui.QPushButton("开始执行")
        btn_run.clicked.connect(lambda:g_mainwin.close())

        btn = QtGui.QPushButton("选择目标区域")
        btn.clicked.connect(self.btn_click_msg)
        btn_ocr = QtGui.QPushButton("ocr识别")
        btn_ocr.clicked.connect(self.btn_click_ocr)
        btn_testocr = QtGui.QPushButton("学习")
        btn_testocr.clicked.connect(self.btn_click_imgDetect)

        vbox = QtGui.QVBoxLayout()
        vbox.addWidget(b)
        hbox = QtGui.QHBoxLayout()
        hbox.addWidget(btn_succ)
        hbox.addWidget(btn_cmit)
        hbox.addWidget(btn_next)
        vbox.addLayout(hbox)
        vbox.addWidget(btn_run)
        vbox.addWidget(btn)
        vbox.addWidget(btn_ocr)
        vbox.addWidget(btn_testocr)
        self.setLayout(vbox)
        

    def btn_click_msg(self):
        #选择目标识别的区域。
        #QtGui.QMessageBox.information(None, "信息提示", "你点击了我")
        self.on_select_region()
        mouser_opt.setwinPos(self.m_min_x,self.m_min_y,self.m_width,self.m_height)
        img_detect.setwinPos(self.m_min_x,self.m_min_y,self.m_width,self.m_height)

        cut_img=self.m_deskimg[self.m_min_y:self.m_min_y+self.m_height,self.m_min_x:self.m_min_x+self.m_width]
        cv2.imwrite('select_save.png',cut_img)

        #g_mainwin.close()  #界面结束
    def on_select_region(self):
        #通过鼠标选择区域
        pilimg = pyautogui.screenshot()
        self.m_deskimg = cv2.cvtColor(np.array(pilimg), cv2.COLOR_RGB2BGR)
        cv2.namedWindow('image',cv2.WINDOW_AUTOSIZE)
        cv2.setMouseCallback('image',cv2_on_mouse,self)
        cv2.imshow('image',self.m_deskimg)
        cv2.moveWindow('image',0,0)

        screensize = pyautogui.size()
        print("size",screensize)
        rect = cv2.getWindowImageRect('image')
        print("rect",rect)
        cv2.waitKey(0)

        self.m_min_x=min(self.m_ltpoint[0],self.m_rbpoint[0])
        self.m_min_y=min(self.m_ltpoint[1],self.m_rbpoint[1])
        self.m_width=abs(self.m_ltpoint[0]-self.m_rbpoint[0])
        self.m_height=abs(self.m_ltpoint[1]-self.m_rbpoint[1])

    def on_mouse(self,event,x,y,flags):
        #在选择目标区域时，跟踪鼠标，保存选择区域
        img2=self.m_deskimg.copy()
        if event==cv2.EVENT_LBUTTONDOWN:#左键点击
            self.m_ltpoint=(x,y)
            #cv2.circle(img2,self.m_ltpoint,10,(0,255,0),5)
            #cv2.imshow('image',img2)

        elif event==cv2.EVENT_MOUSEMOVE and (flags&cv2.EVENT_FLAG_LBUTTON):#移动鼠标，左键拖拽
            cv2.rectangle(img2,self.m_ltpoint,(x,y),(255,0,0),3)#需要确定的就是矩形的两个点（左上角与右下角），颜色红色，线的类型（不设置就默认）。
            cv2.imshow('image',img2)

        elif event==cv2.EVENT_LBUTTONUP:#左键释放
            self.m_rbpoint=(x,y)
            #cv2.rectangle(img2,self.m_ltpoint,self.m_rbpoint,(0,0,255),5)#需要确定的就是矩形的两个点（左上角与右下角），颜色蓝色，线的类型（不设置就默认）。
            #cv2.imshow('image',img2)
            # min_x=min(self.m_ltpoint[0],self.m_rbpoint[0])
            # min_y=min(self.m_ltpoint[1],self.m_rbpoint[1])
            # width=abs(self.m_ltpoint[0]-self.m_rbpoint[0])
            # height=abs(self.m_ltpoint[1]-self.m_rbpoint[1])
            # cut_img=self.m_deskimg[min_y:min_y+height,min_x:min_x+width]
            # cv2.imwrite('crop_cell_nucleus.png',cut_img)
            cv2.destroyWindow("image")
            pass

    def btn_click_ocr(self):
        #触发一次ocr目标识别
        mouser_opt.click_ocr_opt()
    def btn_click_imgDetect(self):
        #自动图片探测，学习题库
        img_detect.img_detect_main()

    def btns_click(self,id):
        self.on_select_region()
        cut_img=self.m_deskimg[self.m_min_y:self.m_min_y+self.m_height,self.m_min_x:self.m_min_x+self.m_width]
        if(id == 0):
            cv2.imwrite('result_btn.png',cut_img)
        elif(id == 1):
            cv2.imwrite('commit_btn.png',cut_img)
        elif(id == 2):
            cv2.imwrite('next_btn.png',cut_img)



def gui_main():
    global g_mainwin
    app = QtGui.QApplication(sys.argv)

    g_mainwin = mainwindow()
    g_mainwin.show()
    app.exec()
	
if __name__ == '__main__':
   gui_main()